package com.william.jdbcplus.core.query;

import com.william.jdbcplus.common.entity.Entity;
import com.william.jdbcplus.core.meta.TableHelperUtil;
import com.william.jdbcplus.core.toolkit.lambda.LambdaUtils;
import com.william.jdbcplus.core.toolkit.lambda.support.SFunction;

import java.util.HashMap;
import java.util.Map;

public class UpdateWrap<T extends Entity> {
    /**
     * 参数及值保存
     */
    private Map<String, Object> updateMap;

    private Class<T> entityClass;

    private UpdateWrap() {
        updateMap = new HashMap<>();
    }

    public UpdateWrap(Class<T> clazz) {
        this.entityClass = clazz;
        this.updateMap = new HashMap<>();
    }

    /**
     * 获取 columnName
     */
    public String columnToString(SFunction<T, ?> column) {
        String fieldName = LambdaUtils.getFieldProperty(column);
        Class<T> clazz = LambdaUtils.getFuncClass(column);
        String colunmString = TableHelperUtil.getEntityFieldColumn(clazz, fieldName);
        return colunmString;
    }

    /**
     * set 片段
     *
     * @param column
     * @param val
     * @return
     */
    public UpdateWrap<T> set(SFunction<T, ?> column, Object val) {
        updateMap.put(columnToString(column), val);
        return this;
    }

    /**
     * set 片段
     *
     * @param column
     * @param val
     * @return
     */
    public UpdateWrap<T> set(String column, Object val) {
        updateMap.put(column, val);
        return this;
    }

    /**
     * set 对象所有的非空属性
     *
     * @param entity
     * @return
     */
    public UpdateWrap<T> setNotNull(T entity) {
        Map<String, Object> attrMap = TableHelperUtil.getEntityAttrMapWithoutLogicDelete(entity);
        for (Map.Entry<String, Object> attr : attrMap.entrySet()) {
            // 只更新非空属性列
            if (attr.getValue() != null) {
                set(attr.getKey(), attr.getValue());
            }
        }
        return this;
    }

    /**
     * set 对象所有属性,包括实体的空属性
     *
     * @param entity
     * @return
     */
    public UpdateWrap<T> setEntity(T entity) {
        Map<String, Object> attrMap = TableHelperUtil.getEntityAttrMapWithoutLogicDelete(entity);
        for (Map.Entry<String, Object> attr : attrMap.entrySet()) {
            // 只更新非空属性列
            set(attr.getKey(), attr.getValue());
        }
        return this;
    }

    public void clear() {
        updateMap.clear();
    }

    public Map<String, Object> getUpdateMap() {
        return updateMap;
    }

    public Class<T> getEntityClass() {
        return this.entityClass;
    }

}
